﻿using UnityEngine;
using System.Collections;

public class Door : MonoBehaviour {
	public bool open = false;
	bool inExit = false;
	bool ableToExit = false;
	public bool isDecendDoor = false;
	public bool locked = false;
	GameObject doorMove;
	void Start() {
		doorMove = transform.Find ("DoorMove").gameObject;
	}
	void Update() {
		if(doorMove != null)
			doorMove.transform.localPosition = Vector3.Lerp (doorMove.transform.localPosition, (open) ? new Vector3 (1, 0, -.01f) : new Vector3 (0, 0, -.01f), Time.deltaTime * 10);
		else
			doorMove = transform.Find ("DoorMove").gameObject;
		if(open && !ableToExit && !inExit) ableToExit = true;
		if(open && ableToExit && inExit) GameObject.FindGameObjectWithTag("StateManager").GetComponent<GameStateManager>().AdvanceLevel();
	}
	public void OpenDoor(){
		if (!locked) {
			if (!isDecendDoor)
				GetComponent<BoxCollider> ().enabled = false;
			transform.Find ("light").GetComponent<Light> ().enabled = true;
			open = true;
		}
	}
	public void CloseDoor() {
		GetComponent<BoxCollider>().enabled = true;
		transform.Find("light").GetComponent<Light>().enabled = false;
		open = false;
	}
	void OnTriggerEnter(Collider other) {
		if(other.tag == "Player") {
			inExit = true;
		};
	}

	void OnTriggerExit(Collider other) {
		if(other.tag == "Player")
			inExit = false;
	}
}

